<template>
  <div class="data-auth-encrypt">
    <p>数据权限 - 敏感信息加密</p>
    <div class="col-wrap">
      <div class="col-content">
        <div class="content-wrap" v-loading="loading">
          <div class="title">已配置的加密信息</div>
          <div class="content-handler">
            <span class="item select">标签</span>
            <el-input v-model="keyword" placeholder="输入搜索关键字" @keyup.native.enter="search">
              <i class="el-icon-close" slot="suffix" @click="clearSearch" v-if="keyword.length"></i>
              <el-button slot="append" @click="search"><icon-svg name="iconSearch"></icon-svg></el-button>
            </el-input>
          </div>
          <div class="list-content">
            <div v-if="selected.length && selected[selected.length - 1].catalogId" class="tab-title">
              <icon-svg name="iconReturn" @click.native="prev"></icon-svg>
              <el-breadcrumb separator="/" ref="factoryBread">
                <div class="elli" v-if="breadLeft < 0">...</div>
                <el-breadcrumb-item
                  v-for="(item, index) in selected"
                  :key="index"
                  :class="{ normal: index === selected.length - 1 }"
                  :style="index === 0 ? { marginLeft: breadLeft + 'px' } : null"
                  @click.native="changeTab(index)"
                  >{{ item.catalogNm }}</el-breadcrumb-item
                >
              </el-breadcrumb>
            </div>
            <template v-if="showList.length && showList[0].tagId">
              <ul class="list tag-scrollbar">
                <li v-for="item in showList" :key="item.tagId" class="list-item">
                  <div class="asset-name">{{ item.tagNm }}</div>
                  <!-- 增加已选标识 -->
                  <div class="list-handler" v-show="editing">
                    <span v-if="isConfig(item)">已配置</span>
                    <el-tooltip effect="dark" content="添加" placement="top" :enterable="false" v-else>
                      <icon-svg name="iconCircleAdd" class="svg-edit" @click.native="editEncrypt(item)"></icon-svg>
                    </el-tooltip>
                  </div>
                </li>
              </ul>
              <el-pagination
                @current-change="handleCurrentChange"
                :current-page="params.currentPageNum"
                :page-size="params.pageSize"
                :pager-count="5"
                background
                layout="total, prev, pager, next"
                small
                :total="totalSize"
              >
              </el-pagination>
            </template>
            <ul v-else-if="showList.length && showList[0].catalogId" class="list catalog-list tag-scrollbar">
              <li v-for="item in showList" :key="item.catalogId" @click="handleClickCatalog(item)" class="list-item">
                {{ item.catalogNm }} （{{ item.dataAssetCount }}）
                <i class="el-icon-arrow-right"></i>
              </li>
            </ul>
            <p v-else>{{ loading ? '' : '暂无内容' }}</p>
          </div>
          <div class="content-info"><i class="el-icon-d-arrow-right"></i></div>
          <div class="content-list tag-scrollbar">
            <el-card shadow="never">
              <tag-table
                ref="table"
                @refresh="getList"
                :data="dataList"
                :loading="tableLoading"
                :columns="columns"
                :pagination="false"
                :height="457"
              >
                <template #operation="{ scope }">
                  <div class="operation-button-box">
                    <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
                      <icon-svg name="iconEdit" class="svg-edit" @click.native="editEncrypt(scope.row)"></icon-svg>
                    </el-tooltip>
                    <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                      <icon-svg
                        name="iconDelete"
                        class="svg-delete"
                        @click.native="deleteEncrypt(scope.row)"
                      ></icon-svg>
                    </el-tooltip>
                  </div>
                </template>
              </tag-table>
            </el-card>
          </div>
        </div>
      </div>
    </div>
    <el-row>
      <el-col :span="24" align="right">
        <template v-if="!editing">
          <el-button type="primary" @click="handleEdit">修改</el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click="cancelEdit">确定</el-button>
        </template>
      </el-col>
    </el-row>
    <encrypt-dialog ref="encryptDialog" @callback="getList"></encrypt-dialog>
  </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
import encryptDialog from './data-auth-encrypt-dialog'
export default {
  components: {
    encryptDialog
  },
  data() {
    return {
      loading: false,
      tableLoading: false,
      editing: false,
      // 体系
      catalogList: [],
      // 表格数据
      dataList: [],
      columns: [
        {
          show: true,
          label: '标签名称',
          prop: 'tagNm',
          search: true,
          searchKey: ''
        },
        {
          show: true,
          label: '使用符号',
          prop: 'useSymbol',
          search: true,
          searchKey: '',
          align: 'center'
        },
        {
          show: true,
          label: '起始位置',
          prop: 'startSite',
          align: 'center'
        },
        {
          show: true,
          label: '结束位置',
          prop: 'endSite',
          align: 'center'
        },
        {
          show: false,
          label: '操作',
          prop: 'operation',
          align: 'center',
          width: 100
        }
      ],
      params: {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      },
      totalSize: 0,
      selected: [],
      breadLeft: 0,
      keyword: ''
    }
  },
  computed: {
    showList() {
      if (!this.selected.length) return cloneDeep(this.catalogList)
      else {
        return this.selected[this.selected.length - 1]._children
      }
    }
  },
  methods: {
    getParams() {
      this.getCatalogList()
      this.getList()
    },
    getList() {
      this.tableLoading = true
      this.$ajax({
        url: this.$ajax.setUrl('ast/astTagDerivedAuth/sen'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.dataList = data.data
        } else {
          this.$message.error(data.msg)
        }
        this.tableLoading = false
      })
    },
    editEncrypt(item) {
      this.$refs.encryptDialog.showDialog(item)
    },
    deleteEncrypt(item) {
      this.$confirm('确认删除【' + item.tagNm + '】的加密配置？')
        .then(() => {
          this.$ajax({
            url: this.$ajax.setUrl(`ast/astTagDerivedAuth/sen/delete/${item.tagId}`),
            method: 'delete',
            params: this.$ajax.setParams()
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.getList()
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$message.error(data.data || data.msg)
            }
          })
        })
        .catch(() => {
          return
        })
    },
    handleClickCatalog(item) {
      if (item.tail) {
        let result = Object.assign({}, item, { _children: [] })
        this.selected.push(result)
        this.getResults(item)
      } else {
        if (!item._children || !item._children.length)
          item._children = this.findCatalog(cloneDeep(this.catalogList), item.catalogId)
        this.selected.push(item)
      }
      this.getBreadStyle()
    },
    getBreadStyle() {
      // 面包屑样式
      this.$nextTick(() => {
        let totalWidth = 0
        let breadLeft = 0
        const bread = this.$refs.factoryBread
        if (bread) {
          let breadWidth = bread.$el.clientWidth
          for (let i = 0; i < bread.$children.length; i++) {
            totalWidth += bread.$children[i].$el.clientWidth
          }
          if (totalWidth > breadWidth) breadLeft = -(totalWidth - breadWidth + 20)
        }
        this.breadLeft = breadLeft
      })
    },
    getCatalogList() {
      this.$ajax({
        url: this.$ajax.setUrl('dcl/dclAssetCatalog/baseCatalogClass'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          if (data.data && data.data.length) {
            var catalogs = this.$utils.arrayToTree(data.data.slice(1), {
              id: 'catalogId',
              pid: 'parentCatalogId',
              mainSort: 'catalogLevel'
            })
            this.catalogList = catalogs
          }
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },

    handleCurrentChange(val) {
      this.params.currentPageNum = val
      this.getResults()
    },
    search() {
      if (!this.keyword.trim().length) {
        if (!this.selected.length || !this.selected[0].catalogId) this.selected = []
        else this.clearSearch()
        return
      }
      this.params = {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      }
      this.getResults()
    },
    getResults(item) {
      this.loading = true
      this.params.queryParams.tagNm = this.keyword
      if (item && item.catalogId) this.params.queryParams.catalogId = item.catalogId
      else if (this.selected.length)
        this.params.queryParams.catalogId = this.selected[this.selected.length - 1].catalogId
      this.$ajax({
        url: this.$ajax.setUrl('dcl/dclAssetCatalogMount/pageList'),
        method: 'get',
        params: this.$ajax.setParams(this.params)
      }).then(({ data }) => {
        if (data && data.code === '0') {
          if (this.selected.length) this.selected[this.selected.length - 1]._children = data.data.records
          else {
            this.selected.push({ _children: data.data.records })
          }
          this.totalSize = data.data.totalSize
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    },

    prev() {
      this.params = {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      }
      this.totalSize = 0
      this.keyword = ''
      this.selected.splice(this.selected.length - 1, 1)
      this.getBreadStyle()
    },
    findCatalog(list, targetId) {
      var children = []
      for (let i = 0; i < list.length; i++) {
        if (list[i].catalogId === targetId) {
          children = list[i]._children || []
          break
        } else {
          if (list[i]._children) {
            children = this.findCatalog(list[i]._children, targetId)
            if (children.length) break
          }
        }
      }
      return children
    },
    changeTab(index) {
      if (index === this.selected.length - 1) return
      this.keyword = ''
      this.selected.splice(index + 1)
      this.getBreadStyle()
    },
    clearSearch() {
      this.keyword = ''
      if (this.selected[this.selected.length - 1].catalogId) {
        if (this.selected[this.selected.length - 1].tail) {
          this.getResults(this.selected[this.selected.length - 1])
        } else {
          this.selected[this.selected.length - 1]._children = this.findCatalog(
            cloneDeep(this.catalogList),
            this.selected[this.selected.length - 1].catalogId
          )
        }
      } else this.selected.splice(this.selected.length - 1, 1)
    },
    handleEdit() {
      this.editing = true
      this.columns[this.columns.length - 1].show = 'fixed'
    },
    cancelEdit() {
      this.editing = false
      this.columns[this.columns.length - 1].show = false
    },
    isConfig(item) {
      return this.dataList.find(tag => tag.tagId === item.tagId)
    }
  }
}
</script>

<style lang="scss">
$bg-color: #4d81ea;
.data-auth-encrypt {
  .col-wrap {
    height: 520px;
    padding-top: 40px;
    margin-bottom: 20px;
    display: flex;
  }
  .tag-table .header-cell-class.is-leaf {
    background-color: transparent;
    color: $bg-color;
    border-bottom-color: transparent;
  }
  .tag-table .header-cell-class .cell {
    font-size: 15px;
    line-height: 30px;
  }
  .el-table::before {
    display: none;
  }
  .el-card {
    border-radius: 0;
  }
  .el-card__body {
    padding: 10px;
  }
  .el-table--striped .el-table__body tr.el-table__row--striped td {
    background: #fff;
  }
  .el-table--striped .el-table__body tr td {
    background: #fafafa;
  }
  .col-content {
    flex: 1;
  }
  .content-wrap {
    height: 100%;
    border: 1px solid #eee;
    position: relative;
    .tag-scrollbar .el-card .operation-button-box svg {
      width: 20px;
      height: 20px;
      cursor: pointer;
    }
  }
  .title {
    font-size: 14px;
    width: 45%;
    text-align: center;
    position: absolute;
    left: 55%;
    top: -30px;
  }
  .content-handler {
    width: 45%;
    position: absolute;
    top: -40px;
    left: -1px;
    .item {
      display: inline-block;
      width: 100px;
      height: 40px;
      text-align: center;
      line-height: 40px;
      padding: 0 20px;
      border: 1px solid #eee;
      border-bottom-color: #fff;
      border-top-left-radius: 10px;
      border-top-right-radius: 10px;
      background-color: #e4efff;
      cursor: pointer;
      &.select {
        color: #fff;
        background-color: $bg-color;
        border-bottom-color: #eee;
      }
    }
    .el-input {
      width: calc(100% - 250px);
      float: right;
      margin-right: -1px;
      .el-input__suffix {
        top: 12px;
      }
      .el-input-group__append {
        color: #fff;
        background-color: $bg-color;
        border-color: $bg-color;
      }
    }
  }
  .list-content {
    float: left;
    width: 45%;
    height: 100%;
    padding-top: 10px;
    border-right: 1px solid #ddd;
    overflow-y: auto;
    .tab-title {
      font-size: 15px;
      font-weight: bold;
      padding: 5px 0 10px 45px;
      color: $bg-color;
      position: relative;
      .el-breadcrumb__inner {
        color: $bg-color;
        cursor: pointer;
        &:hover {
          color: $bg-color;
        }
      }
      .el-breadcrumb__item.normal .el-breadcrumb__inner {
        font-weight: normal;
      }
      svg {
        width: 18px;
        height: 18px;
        position: absolute;
        left: 20px;
        top: 2px;
        cursor: pointer;
      }
    }
    ul.list {
      height: calc(100% - 30px - 30px);
      padding: 0 10px;
      overflow-y: auto;
      &.catalog-list {
        height: calc(100% - 10px);
      }
      .list-item {
        padding: 0 30px 0 20px;
        line-height: 40px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        cursor: pointer;
        position: relative;
        &:hover {
          background-color: #ebf2f9;
        }
        .el-icon-arrow-right {
          position: absolute;
          top: 15px;
          right: 15px;
        }
        .list-handler {
          position: absolute;
          top: 0;
          right: 12px;
          color: $bg-color;
          svg {
            width: 20px;
            height: 20px;
            margin-top: 10px;
            cursor: pointer;
          }
          .el-button {
            width: 25px;
            height: 25px;
          }
          .tip {
            display: block;
            height: 40px;
            margin-top: -7px;
            color: $theme-color;
          }
          .el-button--mini.is-circle {
            padding: 6px;
          }
        }
      }
    }
    p {
      line-height: 40px;
      text-align: center;
    }
  }
  .elli {
    width: 16px;
    height: 100%;
    content: '...';
    line-height: 10px;
    background-color: #f0f4f7;
    position: absolute;
    top: 0;
    left: 0;
  }
  .content-info {
    float: left;
    width: 10%;
    text-align: center;
    i {
      color: $theme-color;
      font-size: 30px;
      margin-top: 175px;
    }
  }
  .el-pagination {
    text-align: right;
  }
  .list-item {
    line-height: 40px;
    padding: 0 90px 0 20px;
    position: relative;
  }
  .operation-button-box svg {
    width: 20px;
    height: 20px;
    cursor: pointer;
  }
}
</style>
